import type { FC } from 'react';
import { Card, Col, Row, Space, Calendar, Popover, Tabs } from 'antd';
import unReadMessage from '@/assets/unReadMessage.png'
import work from '@/assets/work.jpg'
import award from '@/assets/award.png'
import time from '@/assets/time.png'
import React, { useEffect, useState } from 'react';
import type { TabsProps } from 'antd';
import ActivityTable from '@/pages/dashboard/workplace/components/ActivityTable';
// import EventLegend  from '@/pages/dashboard/workplace/components/EventLegend';
import { useHistory } from 'react-router-dom';
import {
  getactivityList,
  getcurTimeActivities,
  getReportAndActivity,
} from '@/services/workplace'
import { connect, useDispatch } from 'umi';
import moment from 'moment';
import 'moment/locale/zh-cn';
import './index.less'
import { getRandomColor, colors } from '@/utils/randomcolor';
moment.locale('zh-cn');

interface DataType {
  key: string;
  activityLabel: string;
  organizationalUnit: string;
  activityAddress: string;
  startTime: string;
  endTime: string;
}
const filteredData = (activityList: DataType[]) => {
  const levelZeroData: DataType[] = [];
  const levelOneData: DataType[] = [];
  const levelTwoData: DataType[] = [];
  const levelThreeData: DataType[] = [];

  for (const item of activityList) {
    switch (item.activityLevel) {
      case '0':
        levelZeroData.push(item);
        break;
      case '1':
        levelOneData.push(item);
        break;
      case '2':
        levelTwoData.push(item);
        break;
      case '3':
        levelThreeData.push(item);
        break;
      default:
        break;
    }
  }

  return {
    levelZeroData,
    levelOneData,
    levelTwoData,
    levelThreeData,
  };
};

const Workplace: FC = () => {
  const history = useHistory();
  const [activeList, setactiveList] = useState(null);//全部活动
  const [levelZeroData, setLevelZeroData] = useState(null);//国家级活动
  const [levelOneData, setLevelOneData] = useState(null);//省级活动
  const [levelTwoData, setLevelTwoData] = useState(null);//校级活动
  const [levelThreeData, setLevelThreeData] = useState(null);//院级活动
  const items: TabsProps['items'] = [
    {
      key: '1',
      label: `全部`,
      children: <ActivityTable activeList={activeList} />,
    },
    {
      key: '2',
      label: `国家级`,
      children: <ActivityTable activeList={levelZeroData} />,
    },
    {
      key: '3',
      label: `省市级`,
      children: <ActivityTable activeList={levelOneData} />,
    },
    {
      key: '4',
      label: `校级`,
      children: <ActivityTable activeList={levelTwoData} />,
    },
    {
      key: '5',
      label: `院级`,
      children: <ActivityTable activeList={levelThreeData} />,
    },
  ];
  const [tableListData, setTableListData] = useState(null);//未读通知数量
  const [events, setEvents] = useState([]);
  const [results, setResults] = useState({
    activity: [],
    notify: [],
  });

  const dispatch = useDispatch();

  useEffect(() => {//处理未读通知个数
    fetchData();
    fetchCalendarData();
    fetchNoticeAndActivityData();
    dispatch({
      type: 'Model_noticeforstuModel/getNoticeListEffects',
      payload: {
        code: localStorage.getItem('userAccount'),
        callback: (value: any) => {
          // console.log(value)
          const unReadMessage = value.filter((item) => item.status == '0')
          // console.log(unReadMessage)
          setTableListData(unReadMessage.length);
        },
      },
    });
  }, []);
  const fetchData = async () => {//获取活动列表
    try {
      const response = await getactivityList(null, null);
      if (response && response.result) {
        setactiveList(response.result);
        console.log(response.result)
        const { levelZeroData, levelOneData, levelTwoData, levelThreeData } = filteredData(response.result);
        // 存储切分后的数据
        setLevelZeroData(levelZeroData);
        setLevelOneData(levelOneData);
        setLevelTwoData(levelTwoData);
        setLevelThreeData(levelThreeData);
      }
    } catch (error) {
      console.error('Error fetching user info:', error);
    }
  };
  const fetchCalendarData = async () => {//获取日历活动
    try {
      const response = await getcurTimeActivities(null, localStorage.getItem('userAccount'));
      // console.log(response);
      if (response && response.result) {
        setEvents(response.result);
        // console.log(response.result)
      }
    } catch (error) {
      console.error('Error fetching user info:', error);
    }
  };
  const fetchNoticeAndActivityData = async () => {//获取通知和活动
    try {
      const response = await getReportAndActivity(null, localStorage.getItem('userAccount'));
      // console.log(response.result);
      if (response && response.result) {
        setResults(response.result)
        // console.log(results)
      }
    } catch (error) {
      console.error('Error fetching user info:', error);
    }
  };
  /*
  css样式
  --------------------------------------------------------------------------------------------------
   */
  const textStyle = {
    width: 100,
    height: 60,
    marginTop: 0,
    marginLeft: '15%',
    cursor: 'pointer'
  };

  const imageStyle = {
    width: 60,
    height: 60,
    objectFit: 'cover',
    marginLeft: 5,
    marginTop: 5,
    marginBottom: 5,
  };

  const notificationStyle = {
    fontWeight: 'bold',
    fontSize: '20px',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    textAlign: 'justify'
  };

  const countStyle = {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    textAlign: 'justify',
    color: 'red',
    fontSize: '30px',
    fontWeight: 'bold',
  };
  // ...

  const colorMap = {};

  // 在组件中添加一个状态来保存颜色索引
  const [colorIndex, setColorIndex] = useState(0);

  // 在 useEffect 钩子中更新颜色索引
  useEffect(() => {
    setColorIndex((prevIndex) => (prevIndex + 1) % colors.length);
  }, []);

  // 在 dateCellRender 函数中使用当前的颜色索引
  const dateCellRender = (date) => {
    const dateStr = date.format('YYYY-MM-DD');//设置日历格式

    const eventsOnDate = events?.filter(//过滤出特定日期相关的所有活动
      (event) => moment(event.startTime).isSameOrBefore(dateStr, 'day') && moment(event.endTime).isSameOrAfter(dateStr, 'day')
    );

    // console.log(eventsOnDate)
    if (eventsOnDate?.length > 0) {
      return (
        <Popover
          content={eventsOnDate.map(event => (
            <div key={event.id} style={{ color: colorMap[Number(event.id) % 10] }}>
              {event.activityLabel}
            </div>
          ))}
          title={moment(dateStr).format('YYYY-MM-DD')}
        >
          <div className="event-dots" style={{ display: 'flex', justifyContent: 'center' }}>
            {eventsOnDate.map(event => {
              if (!colorMap[Number(event.id) % 10]) {
                colorMap[Number(event.id) % 10] = getRandomColor();
              }

              return (
                <div
                  key={event.id}
                  className="event-dot"
                  style={{
                    backgroundColor: colorMap[Number(event.id) % 10],
                    width: '10px', // 设置宽度为一个固定值
                    height: '10px',
                    borderRadius: '50%', // 使颜色点呈现圆形
                    margin: '0 2px', // 设置颜色点之间的间距
                  }}
                />
              );
            })}
          </div>
        </Popover>
      );
    }
    return null;
  };
  if (events === null || events === undefined) {
    return <p>Loading...</p>;
  }

  /*
  --------------------------------------------------------------------------------------------------
  css样式
 */
  return (
    <Row gutter={24}>
      <Col xl={18} lg={24} md={24} sm={24} xs={24}>
        {/* 左上 */}
        <Card
          style={{ marginBottom: 24 }}
          title={
            <div>
              <span role="img" aria-label="Welcome"><b>👏欢迎回来，{localStorage.getItem('userName')}</b></span><br /><br />
            </div>
          }
          bordered={false}
          bodyStyle={{ padding: 0 }}
        >
          <Card.Grid key="1">
            <Card bodyStyle={{ padding: 0 }} bordered={false} onClick={() => history.push('/notification/list')}>
              <span>
                <img
                  src={unReadMessage}
                  alt="未读通知"
                  style={imageStyle}
                />
              </span>
              <span style={textStyle}>
                <div style={notificationStyle}>未读通知</div>
                <div style={countStyle}>{tableListData}</div>
              </span>
            </Card>
          </Card.Grid>
          <Card.Grid key="2">
            <Card bodyStyle={{ padding: 0 }} bordered={false} onClick={() => {
              if (localStorage.getItem("roleId") != '2'){
                history.push('/activityInfo/activityList')
              }else {
                history.push('/activityInfoTeacher/activityList')
              }
            }}>
              <span>
                <img
                  src={work}
                  alt="我的活动"
                  style={imageStyle}
                />
              </span>
              <span style={textStyle}>
                <div style={notificationStyle}>我的活动</div>
                <div style={countStyle}>1</div>
              </span>
            </Card>
          </Card.Grid>
        </Card>
        {/* 左中 */}
        <Card title={
          <div><b>我的事务</b></div>
        } style={{ marginBottom: 24 }}
          bordered={false}>
          <Space direction="horizontal" size="middle" style={{ display: 'flex' }} align="center">
            <Space direction="vertical" size="middle" style={{ display: 'flex' }} align="center">
              <img
                src={time}
                alt="请假审批"
                style={{
                  width: 100,
                  height: 100,
                  cursor: 'pointer'
                }}
              />
              <div><b>请假审批</b></div>
            </Space>
            <span>&nbsp;&nbsp;&nbsp;&nbsp;</span>
            <Space direction="vertical" size="middle" style={{ display: 'flex' }} align="center">
              <img
                src={award}
                alt="获奖审批"
                style={{
                  width: 100,
                  height: 100,
                  cursor: 'pointer'
                }}
              />
              <div><b>获奖审批</b></div>
            </Space>
          </Space>
        </Card>
        {/* 左下列表 */}
        <Card
          title={
            <div><b>热门活动</b></div>
          }
          extra={<a>查看更多</a>}
          bordered={false}>
          <Tabs defaultActiveKey="1" items={items} />
        </Card>

      </Col>
      <Col xl={6} lg={24} md={24} sm={24} xs={24}>

        {/* 右上日历 */}
        <Card style={{ marginBottom: 24 }}>
          <div style={{ width: "100%", height: 415 }}>
            {/* <EventLegend colorMap={colorMap} events={events} /> */}
            <Calendar
              fullscreen={false}
              dateCellRender={dateCellRender}
              locale="zh-cn"
            />
          </div>
        </Card>
        {/* 右下活动和通知的集合 */}
        <Card style={{ marginBottom: 24, height: 320 }} title={<b>通知公告</b>} extra={<a>查看更多</a>}>
          <div style={{ overflowY: 'auto', height: 220 }}>
            {/* 遍历活动，并将活动名称显示在通知下方 */}
            {results.activity &&
              results.activity.map((activity, index) => (
                <div key={index} style={{ marginBottom: 10, width: '90%', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>
                  <span style={{ background: '#FFF7E8', borderRadius: '10%', color: '#FF7D00', padding: '5px 10px' }}>活动</span>
                  &nbsp;&nbsp;<span style={{ color: '#4E5969' }}>{activity}</span>
                </div>
              ))}
            {/* 其他通知内容 */}
            {results.notify &&
              results.notify.map((notify, index) => (
                <div key={index} style={{ marginBottom: 10, width: '90%', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>
                  <span style={{ background: '#E8F3FF', borderRadius: '10%', color: '#165DFF', padding: '5px 10px' }}>通知</span>
                  &nbsp;&nbsp;<span style={{ color: '#4E5969' }}>{notify}</span>
                </div>
              ))}

          </div>
        </Card>
      </Col>
    </Row>
  );
};

export default connect(({ Model_noticeforstuModel }: any) => ({
  Model_noticeforstuModel,
}))(Workplace);

